package org.langcom.logic;

import org.apache.commons.lang.BooleanUtils;

public abstract class AbstractLogic implements ILogic {

	private static final long serialVersionUID = -8706809982007919245L;
	private final String description;
	private final String detailedDescription;
	protected boolean checkingImpossible = false;
	protected String impossibilityCause = "";//$NON-NLS-1$

	protected abstract boolean tryOn() throws Exception;

	protected AbstractLogic(String description, String detailedDescription) {
		this.description = description;
		this.detailedDescription = detailedDescription;
	}

	public String getDescription() {
		return description;
	}

	public String getDetailedDescription() {
		if (checkingImpossible) {
			return detailedDescription + " : " + Messages.AbstractLogic_1; //$NON-NLS-1$
		}
		return detailedDescription;
	}

	@SuppressWarnings("nls")
	@Override
	public String toString() {
		if (checkingImpossible) {
			return description + " : " + Messages.AbstractLogic_1;
		}
		return description + " : " + BooleanUtils.toString(check(), Messages.AbstractLogicNode_0, Messages.AbstractLogicNode_1);
	}

	public void setImpossible(boolean value, String cause) {
		checkingImpossible = value;
		impossibilityCause = cause;
	}

	public final boolean check() {
		impossibilityCause = ""; //$NON-NLS-1$
		checkingImpossible = false;
		try {
			return tryOn();
		} catch (Exception e) {
			impossibilityCause = e.getLocalizedMessage();
			checkingImpossible = true;
			return false;
		}
	}

	public boolean isImpossibleChecking() {
		return checkingImpossible;
	}

	public String getImpossibilityCause() {
		return impossibilityCause;
	}
}
